package org.softmed.neodatis.util.id;

import org.neodatis.odb.ODB;
import org.softmed.neodatis.util.id.generator.IDGenerator;
import org.softmed.neodatis.util.provider.ODBProvider;
import org.softmed.reflection.utils.FieldInfo;
import org.softmed.reflection.utils.ReflectionUtil;

public class GenerateIDConfigurator {

	ReflectionUtil rutil = new ReflectionUtil();
	GenerateIDTrigger generateIDTrigger = new GenerateIDTrigger();
	ODBProvider provider;

	public GenerateIDConfigurator(ODBProvider provider) {
		this.provider = provider;
	}

	protected void registerGenerator(Class type, String fieldName,
			IDGenerator generator, boolean replace) throws Throwable {

		FieldInfo fieldInfo = rutil.getFieldInfo(type, fieldName);
		if (fieldInfo == null)
			throw new RuntimeException("The class " + type
					+ " has no field named " + fieldName
					+ ". Can't register generator.");

		ODB odb = null;
		try {
			odb = provider.getODB();
			generateIDTrigger.getStoredGenerators(odb);
			generateIDTrigger.getClassFieldIDGenerators().registerGenerator(
					type, fieldName, generator, replace);
			generateIDTrigger.getClassIDFieldRegistration().register(type,
					fieldName);
			generateIDTrigger.storeGenerators(odb);
			odb.close();
		} catch (Throwable e) {
			e.printStackTrace();
			if (odb != null) {
				try {
					odb.close();
					odb = null;
				} catch (Exception t) {
					t.printStackTrace();
				}
			}
		}

	}

	public void disableAllInheritedGeneratedFields(Class type) {
		generateIDTrigger.getClassIDFieldRegistration()
				.disableAllInheritedGeneratedFields(type);
	}

	public void disableInheritedGeneratedField(Class type, String fieldName)
			throws Throwable {
		generateIDTrigger.getClassIDFieldRegistration()
				.disableInheritedGeneratedField(type, fieldName);
	}

	public void replaceGenerator(Class type, String fieldName,
			IDGenerator generator) throws Throwable {
		registerGenerator(type, fieldName, generator, true);
	}

	public void registerGenerator(Class type, String fieldName,
			IDGenerator generator) throws Throwable {
		registerGenerator(type, fieldName, generator, false);
	}

	public GenerateIDTrigger getGenerateIDTrigger() {
		return generateIDTrigger;
	}

}
